package com.boarsoft.boar.gateway.web.handler;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.ConcurrentHashMap;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.eclipse.jetty.http.HttpStatus;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.boarsoft.boar.gateway.GatewayConfig;
import com.boarsoft.boar.gateway.web.GatewayHttpServlet;
import com.boarsoft.common.Util;
import com.boarsoft.common.util.RandomUtil;
import com.boarsoft.config.core.Configable;
import com.boarsoft.soagov.svc.ServiceAdapter;
import com.boarsoft.webapp.HttpServiceHandler;

public class Card3rdHttpHandlerImpl implements HttpServiceHandler, Configable {
	private static final Logger log = LoggerFactory.getLogger(GatewayHttpServlet.class);

	/** */
	protected Map<String, ServiceAdapter> adapterMap = new HashMap<String, ServiceAdapter>();
	/** */
	protected Properties prop = new Properties();
	/** { bank: { channel: weight } } 冗余每个channel的weight */
	protected Map<String, Map<String, Integer>> cacheMap = //
			new ConcurrentHashMap<String, Map<String, Integer>>();

	@Override
	public void config() {
		ClassLoader cl = GatewayConfig.class.getClassLoader();
		try {
			log.info("Load conf/card3rd.properties ...");
			synchronized (prop) {
				prop.clear();
				prop.load(cl.getResourceAsStream("conf/card3rd.properties"));
			}
			// TODO 解析properties构建并填充cacheMap
			//
		} catch (IOException e) {
			log.error("Error on load conf/card3rd.properties.", e);
		}
	}

	@Override
	public boolean process(HttpServletRequest req, HttpServletResponse rsp) throws ServletException, IOException {
		// TODO 将报文转成java bean
		Object obj = "{ bank: \"A\", card: \"123456789\" }";
		// TODO 取报文中的他行卡归属行
		String bank = "A";
		if (Util.strIsEmpty(bank)) {
			rsp.sendError(HttpStatus.BAD_REQUEST_400);
			return true;
		}
		// 检查并获取支持此银行的核验渠道
		if (cacheMap.containsKey(bank)) {
			rsp.sendError(HttpStatus.NOT_ACCEPTABLE_406);
			return true;
		}
		// 根据每个渠道的权重随机选择其中一个渠道编号
		String sa = RandomUtil.random(cacheMap.get(bank));
		// 如果没有找到服务提供者，则返回服务不可用
		if (Util.strIsEmpty(sa)) {
			rsp.sendError(HttpStatus.SERVICE_UNAVAILABLE_503);
			return true;
		}
		// 根据选定的渠道适配器调用对应渠道API
		ServiceAdapter adapter = adapterMap.get(sa);
		adapter.process(obj);
		return true; // 永不转发
	}
}